package com.example.usermanager.controller;

import com.example.usermanager.mapper.UserMapper;
import com.example.usermanager.model.UserInfo;
import com.example.usermanager.tools.AppFinal;
import com.example.usermanager.tools.ResponseBody;
import com.example.usermanager.tools.SessionUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserMapper userMapper;
    @RequestMapping("/login")
    public ResponseBody<UserInfo> login(@RequestParam String username, @RequestParam String password,HttpServletRequest request){
        UserInfo userInfo=userMapper.login(username,password);
        int status=-1;
        String message="用户名或密码错误";
        if (userInfo!=null&&userInfo.getId()>0){
            status=1;
            HttpSession session=request.getSession(true);
            session.setAttribute(AppFinal.USERINFO_SESSION_KEY,userInfo);
        }
        return new ResponseBody<>(status,message,userInfo);
    }
    @RequestMapping("/checkadmin")
    public ResponseBody<Integer> checkAdmin(HttpServletRequest request){
        int data=0;
        HttpSession session=request.getSession(false);
        UserInfo userInfo=null;
        if (session!=null&&(userInfo= (UserInfo) session.getAttribute(AppFinal.USERINFO_SESSION_KEY))!=null){
            data=userInfo.getIsadmin();
        }
        return new ResponseBody<>(0,"",data);
    }
    @RequestMapping("/add")
    public ResponseBody<Integer> add(UserInfo userInfo,HttpServletRequest request){
        int data=0;
        int status=0;
        String message="";
        UserInfo info= SessionUtil.getUserBySession(request);
        if (info==null){
            status=-1;
            message="当前用户未登录，请先登录";
        }
        else if (userInfo.getIsadmin()==1){
           if (info.getIsadmin()==0){
                status=-2;
                message="当前用户权限不够";
            }else if (info.getIsadmin()==1){
                data=userMapper.add(userInfo);
            }
        }else if (userInfo.getIsadmin()==0){
            data=userMapper.add(userInfo);
        }
        return new ResponseBody<>(status,message,data);
    }
    @RequestMapping("/getuser")
    public ResponseBody<UserInfo> getUser(@RequestParam int uid){
        int status=-1;
        String message="未知错误";
        UserInfo userInfo=userMapper.getUser(uid);
        if (userInfo!=null){
            status=0;
        }
        return new ResponseBody<>(status,message,userInfo);
    }
    @RequestMapping("/update")
    public ResponseBody<Integer> update(UserInfo userInfo){
        int data=0;
        data=userMapper.update(userInfo);
        return new ResponseBody<>(0,"",data);
    }
}
